﻿using System;
using System.Windows;
using EarthWatchers.SL.Requests;
using EarthWatchers.SL.TIG;
using System.Windows.Controls;
using Earthwatchers.Models;

namespace EarthWatchers.SL.GUI.Controls.Comments
{
    public partial class CommentControl
    {
        private readonly Comment comment;
        private readonly StackPanel holder;
        private readonly TigParser tigParser;

        public CommentControl(StackPanel holder, Comment comment, int landId)
        {            
            InitializeComponent();
            this.holder = holder;
            this.comment = comment;

            if (Current.Instance.Earthwatcher != null && this.comment.EarthwatcherId.Equals(Current.Instance.Earthwatcher.Id) && Current.Instance.TigUserInfo != null)
                SetTigUserInfo(Current.Instance.TigUserInfo);
            else
            {
                tigParser = new TigParser();
                tigParser.TigUserReceived += TigParserTigUserReceived;
                tigParser.GetUserInfo(this.comment.UserName);
            }

            btnRemove.Visibility = Visibility.Collapsed;

            if (Current.Instance.Earthwatcher == null) 
                return;
            
            //Comment is made by the logged in user and is authenticated or land is owned by logged in user
            if (this.comment.EarthwatcherId.Equals(Current.Instance.Earthwatcher.Id) && Current.Instance.IsAuthenticated || (Current.Instance.EarthwatcherLand != null && Current.Instance.EarthwatcherLand.Id == landId))
                btnRemove.Visibility = Visibility.Visible;
        }

        private void TigParserTigUserReceived(object sender, EventArgs e)
        {
            var info = sender as TigUserinfo;
            if (info == null) return;
            SetTigUserInfo(info);
        }

        private void SetTigUserInfo(TigUserinfo info)
        {
            txtHeader.Text = info.Name + " on " + comment.Published.ToLocalTime();
            txtComments.Text = comment.UserComment;
            avatar.Source = info.AvatarBig;
        }

        private void BtnRemoveMouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            var commentRequests = new CommentRequests(Constants.BaseApiUrl);
            commentRequests.Delete(comment.Id,Current.Instance.Username,Current.Instance.Password);
            holder.Children.Remove(this);
        }
    }
}
